package dao

import (
	"TTMS/model"
	"TTMS/utils"
)

// AddTicket 添加票并返回新的票
func AddTicket(ticket *model.Ticket) (*model.Ticket, error) {
	//写 sql 语句
	sqlStr := "insert into tickets(order_id, film_name, col_id, row_id, start_time, end_time, price, order_time, state,user_id,date) values (?,?,?,?,?,?,?,?,?,?,?)"
	//执行
	res, err := utils.DB.Exec(sqlStr, ticket.OrderID, ticket.FilmName, ticket.Col, ticket.Row, ticket.StartTime, ticket.EndTime, ticket.Price, ticket.OrderTime, ticket.State, ticket.UserID, ticket.Date)
	if err != nil {
		return nil, err
	}
	id, _ := res.LastInsertId()
	ticket0 := GetTicketByID(id)
	return ticket0, nil
}

// GetTicketByID 根据票的 id 获取票
func GetTicketByID(ID int64) *model.Ticket {
	//写 sql 语句
	sqlStr := "select id,order_id, film_name, col_id, row_id, start_time, end_time, price, order_time, state, user_id,date from tickets where id=?"
	//执行
	row := utils.DB.QueryRow(sqlStr, ID)
	ticket := &model.Ticket{}
	row.Scan(&ticket.ID, &ticket.OrderID, &ticket.FilmName, &ticket.Col, &ticket.Row, &ticket.StartTime, &ticket.EndTime, &ticket.Price, &ticket.OrderTime, &ticket.State, &ticket.UserID, &ticket.Date)
	return ticket
}

// GetTicketsByUserID 根据用户ID获取电影票
func GetTicketsByUserID(userID int64) ([]*model.Ticket, error) {
	//写 sql 语句
	sqlStr := "select id,order_id, film_name, col_id, row_id, start_time, end_time, price, order_time, state, user_id,date from tickets where user_id=? order by order_time desc"
	//执行
	rows, err := utils.DB.Query(sqlStr, userID)
	if err != nil {
		return nil, err
	}
	var tickets []*model.Ticket
	for rows.Next() {
		ticket := &model.Ticket{}
		rows.Scan(&ticket.ID, &ticket.OrderID, &ticket.FilmName, &ticket.Col, &ticket.Row, &ticket.StartTime, &ticket.EndTime, &ticket.Price, &ticket.OrderTime, &ticket.State, &ticket.UserID, &ticket.Date)
		tickets = append(tickets, ticket)
	}
	return tickets, nil
}

//UpdateTicket 修改票的状态
